use serde::{Deserialize, Serialize};
use std::fs;
use anyhow::Result;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    #[serde(rename = "WX_TOKEN")]
    pub wx_token: String,
    
    #[serde(rename = "WX_ENCODING_AES_KEY")]
    pub wx_encoding_aes_key: String,
    
    #[serde(rename = "WX_WEBHOOK_URL")]
    pub wx_webhook_url: String,
    
    #[serde(rename = "OPEN_AI_SILICOFLOW")]
    pub openai_silicoflow: OpenAIConfig,
    
    #[serde(rename = "SERVER_PORT")]
    pub server_port: u16,
    
    #[serde(default = "default_database_url")]
    pub database_url: String,
    
    #[serde(default = "default_server_host")]
    pub server_host: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenAIConfig {
    #[serde(rename = "URL")]
    pub url: String,
    
    #[serde(rename = "API_KEY")]
    pub api_key: String,
    
    #[serde(rename = "MODEL")]
    pub model: String,
}

fn default_database_url() -> String {
    "sqlite://./data/remindme.db".to_string()
}

fn default_server_host() -> String {
    "0.0.0.0".to_string()
}

impl Config {
    /// 从 config.json 文件加载配置
    pub fn from_file(path: &str) -> Result<Self> {
        let content = fs::read_to_string(path)?;
        let config: Config = serde_json::from_str(&content)?;
        Ok(config)
    }
    
    /// 加载默认配置文件 (config.json)
    pub fn load() -> Result<Self> {
        Self::from_file("config.json")
    }
}
